package com.akk.business;

import com.akk.module.avs.entity.AvsApplyCard;
import com.akk.module.avs.entity.AvsHotBank;
import com.akk.module.avs.entity.AvsIncreRecord;
import com.akk.module.avs.model.request.AvsIncreRecordRequest;
import com.akk.module.avs.service.AvsApplyCardService;
import com.akk.module.avs.service.AvsHotBankService;
import com.akk.module.avs.service.AvsIncreReocrdService;
import com.akk.utils.RestResponse;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import java.util.*;

@Component
public class AvsApplyCardBusiness {

    @Autowired
    private AvsApplyCardService applyCardService;

    @Autowired
    private AvsHotBankService hotBankService;

    @Autowired
    private AvsIncreReocrdService increReocrdService;

    public RestResponse list( Integer page, Integer limit){
        if (page == null || page == 0)
            page = 1;
        if (limit == null || limit == 0)
            limit = 6;
        PageHelper.startPage(page,limit);
        List<AvsApplyCard> list = applyCardService.queryAll();
        return RestResponse.build(list);
    }
    public RestResponse hotBank(){
        List<List<AvsHotBank>> lists = new ArrayList<>();
        Map params = new HashMap();
        params.put("hot",1);
        List<AvsHotBank> list = hotBankService.queryByParams(params);
        if (list.size() > 8){
            int page = 0;
            if (list.size() % 8 == 0)
                page = list.size() / 8;
            else
                page = list.size() / 8 + 1;
            for (int j = 1;j <= page;j++){
                List<AvsHotBank> data = new ArrayList<>();
                for (int i = 0;i < 8;i++){
                    int index = (j-1)*8+i;
                    if (index >= list.size())
                        continue;
                    data.add(list.get(index));
                }
                lists.add(data);
            }
        }else {
            lists.add(list);
        }
        return RestResponse.build(lists);
    }

    public RestResponse saveRecord(AvsIncreRecordRequest recordRequest, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),null);
        AvsIncreRecord increRecord = new AvsIncreRecord();
        increRecord.setRecordPhone(recordRequest.getRecordPhone());
        increRecord.setRecordUsername(recordRequest.getRecordUsername());
        increRecord.setType("card");
        increRecord.setCreateTime(new Date());
        increRecord.setTypeId(recordRequest.getTypeId());
        increReocrdService.save(increRecord);
        return RestResponse.build("success");
    }

}
